import 'dart:convert';
import 'dart:io';

import 'package:flutter_book/config/config.dart';
import 'package:flutter_book/data/model/book_chapter_model.dart';
import 'package:flutter_book/util/string_util.dart';
import 'package:flutter_book/util/extensions/string_extensions.dart';

class BookDataFileUtil {
  static BookDataFileUtil? _util;

  static BookDataFileUtil init() {
    if (_util == null) {
      _util = BookDataFileUtil();
    }
    return _util!;
  }

  //保存章节
  saveFileChapter(BookChapterModel model) {
    if (model.bookId == null || model.id == null || model.cnContent == null) {
      "书籍id:${model.bookId},章节id:${model.id},内容:${model.cnContent == null},有一个是空的，不能存储".print;
      return;
    }
    if (!_isHaveChapterFile(model.bookId ?? "", model.id ?? "")) {
      _writeImageDataToFileChatPage(model);
    }
  }

  Future<bool> getBookChapterContent(BookChapterModel model) async {
    if (model.bookId == null || model.id == null) {
      "书籍id:${model.bookId},章节id:${model.id},有一个是空的，不能获取".print;
    } else {
      if (_isHaveChapterFile(model.bookId ?? "", model.id ?? "")) {
        String filePath = _getBookChapterPath(model.bookId ?? "", model.id ?? "");
        File file = File(filePath);
        model.cnContent = await file.readAsString();
        return true;
      } else {
        "没有这个章节的内容".print;
      }
    }
    return false;
  }

  _writeImageDataToFileChatPage(BookChapterModel model) async {
    await Directory(AppConfig.getAppBookDir() + "/" + (model.bookId ?? "")).create(recursive: true);
    String filePath = _getBookChapterPath(model.bookId ?? "", model.id ?? "");
    File file = File(filePath);
    file.writeAsString(model.cnContent ?? "");

    filePath = _getBookChapterPath(model.bookId ?? "", "${model.id ?? ""}_json");
    file = File(filePath);
    model.cnContent = "";
    file.writeAsString(jsonEncode(model.toJson()));
  }

  bool _isHaveChapterFile(String bookId, String chapterId) {
    String path = _getBookChapterPath(bookId, chapterId);
    if (path.length < 1) {
      return false;
    }
    File file = File(path);
    return file.existsSync();
  }

  _getBookChapterPath(String bookId, String chapterId) {
    return AppConfig.getAppBookDir() + "/" + bookId + "/" + chapterId + ".txt";
  }
}
